#include "hal.h"
#include "mongoose_glue.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include "wd_drv.h"
#include "light_drv.h"

double readVoltage()
{
    char buf[10];
    int fd = open("/sys/bus/iio/devices/iio:device0/in_voltage1_raw", O_RDONLY);
    if (fd < 0) {
        mg_log("open [/sys/bus/iio/devices/iio:device0/in_voltage1_raw] failed");
        return -1;
    }
    int ret = read(fd, buf, sizeof(buf));
    if(ret < 0) {
        mg_log("read [/sys/bus/iio/devices/iio:device0/in_voltage1_raw] failed");
        close(fd);
        return -1;
    }

    close(fd);
    return (double)atoi(buf)/65536*3300; // Convert to volts
}

double readWD(){
    int fd = open("/dev/mywd", O_RDWR);
    int value;
    ioctl(fd, WD_GET, &value);
    value=ntohs(value);
    double ret= 175.72*value/65536-46.85;
    close(fd);
    return ret;
}

double readSD(){
    int fd = open("/dev/mywd", O_RDWR);
    int value;
    ioctl(fd, SD_GET, &value);
    value=ntohs(value);
    double ret= 125.0*value/65536 - 6;
    close(fd);
    return ret;
}

double readLight(){
    int fd = open("/dev/mylight", O_RDWR);
    int value;
    ioctl(fd, LIGHT_GET, &value);
    close(fd);
    return value;
}

void my_get_state(struct state *data)
{
    int value;
    //测温度、湿度
    data->wd = readWD();
    //湿度
    data->sd = readSD();
    //光照
    data->light = readLight();
    //电压值
    value = readVoltage();
    data->voltage = (double)value/65536*3300;
}


void state_init()
{
    mongoose_set_http_handlers("state", my_get_state, NULL);
}
